package com.amkai.mobile.client;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.amkai.mobile.bean.scheduler.appointment.MobileAppointmentBrief;
import com.amkai.mobile.client.SimpleGestureFilter.SimpleGestureListener;
import com.amkai.mobile.client.appointmentdetails.AppointmentDetail;
import com.amkai.mobile.client.common.SharedDataProvider;
import com.amkai.mobile.client.options.OptionsProvider;
import com.amkai.mobile.common.job.scheduler.MobileSchedulerJob;
import com.amkai.mobile.common.job.scheduler.MobileSchedulerJobResult;
import com.amkai.mobile.utils.data.Constants;
import com.amkai.mobile.utils.data.MobileDb;
import com.amkai.mobile.utils.manager.job.MobileServiceManager;

/**
 * 
 * @author peter
 * 
 */
public class Appointments extends Activity implements SimpleGestureListener {
	protected static final int DATE_DIALOG_ID = 0;
	MobileDb mdb;
	private ArrayList<MobileAppointmentBrief> m_appointment = null;
	private AppointmentAdapter m_adapter;
	private SimpleGestureFilter detector;
	private Calendar dateToView = null;
	private ListView lv_appontments = null;
	private TextView tv_date = null;
	private Long currentBEId = null;
	private Long currentPassportId = null;
	MobileSchedulerJobResult result;
	ProgressDialog m_ProgressDialog;
//	final Calendar c = Calendar.getInstance();
//	private int mYear;
//	private int mMonth;
//	private int mDay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.appointments);
		detector = new SimpleGestureFilter(this, this);
		tv_date = (TextView) findViewById(R.id.tv_date);
		lv_appontments = (ListView) findViewById(R.id.lv_appointments);
		dateToView = Calendar.getInstance();
		// tv_date.setText(String.format("%1$tm %1$te,%1$tY", dateToView));
		tv_date.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				showDialog(DATE_DIALOG_ID);
			}
		});
		Bundle b = getIntent().getExtras();
		Button prevButton = (Button) findViewById(R.id.btn_prev);
		prevButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				loadDate(Calendar.DAY_OF_YEAR, -1);
			}
		});

		Button nextButton = (Button) findViewById(R.id.btn_next);
		nextButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				loadDate(Calendar.DAY_OF_YEAR, 1);
			}
		});

		lv_appontments.setOnItemClickListener(new ListView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int index, long arg3) {
				// TODO Auto-generated method stub
				MobileAppointmentBrief mab = result.getMobileAppointmentsBrief().get(index);
				Intent appoinmentDetail = new Intent(Appointments.this, AppointmentDetail.class);
				Bundle b = new Bundle();
				b.putLong(Constants.BUNDLE_CONTENT_TAG_DEPARTMENTID, currentBEId);
				b.putLong(Constants.BUNDLE_CONTENT_TAG_PASSPORTID, currentPassportId);
				b.putLong(Constants.BUNDLE_CONTENT_TAG_APPOINTMENTID, mab.id);
				b.putString(Constants.BUNDLE_CONTENT_TAG_PROVIDERAS, new String(mab.providerAs));
				b.putBoolean(Constants.BUNDLE_CONTENT_TAG_IS_PATIENT, new Boolean(mab.isPatient));
				appoinmentDetail.putExtras(b);
				startActivity(appoinmentDetail);
			}
		});

		currentBEId = b.getLong(Constants.BUNDLE_CONTENT_TAG_DEPARTMENTID);
		currentPassportId = b.getLong(Constants.BUNDLE_CONTENT_TAG_PASSPORTID);

		try {
			updateTitle();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		loadDate(dateToView.DAY_OF_YEAR, 0);

	}

	private void updateTitle() throws Exception {
		SharedDataProvider.getInstance().setAppTitle(Appointments.this, currentBEId);
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {

		case DATE_DIALOG_ID:

			return new DatePickerDialog(this, mDateSetListener, dateToView.get(Calendar.YEAR), dateToView.get(Calendar.MONTH), dateToView.get(Calendar.DAY_OF_MONTH));
		}
		return null;
	}


	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {

		@Override
		public void onDateSet(DatePicker arg0, int year, int monthOfYear, int dayOfMonth) {
//			mYear = year;
//			mMonth = monthOfYear;
//			mDay = dayOfMonth;
			dateToView.set(Calendar.YEAR,year);
			dateToView.set(Calendar.MONTH, monthOfYear);
			dateToView.set(Calendar.DAY_OF_MONTH, dayOfMonth);
			loadDate(dateToView.DAY_OF_YEAR, 0);
//			updateDisplay();
			// TODO Auto-generated method stub

		}
	};

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		switch (id) {
		case DATE_DIALOG_ID:
			((DatePickerDialog) dialog).updateDate(dateToView.get(Calendar.YEAR), dateToView.get(Calendar.MONTH), dateToView.get(Calendar.DAY_OF_MONTH));
//			((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
			break;
		}
	}

	private Calendar constructExpirationDate() {
		Calendar expDay = Calendar.getInstance();
		expDay.set(Calendar.YEAR, Constants.EXPIRATION_YEAR);
		expDay.set(Calendar.MONTH, Constants.EXPIRATION_MONTH);
		expDay.set(Calendar.DAY_OF_MONTH, Constants.EXPIRATION_DAY);
		return expDay;
	}	
	
	private void showAppointments() {
		try {
			// check expiration
			Calendar now = Calendar.getInstance();
			Calendar expDate = constructExpirationDate();
			if (now.before(expDate)) {
				result = MobileServiceManager.processMobileJob(Appointments.this, MobileSchedulerJob.appointmentsBriefBySurgeonAndTimeRange(currentBEId, currentPassportId, dateToView.get(Calendar.YEAR), dateToView.get(Calendar.DAY_OF_YEAR)));
				runOnUiThread(returnRes);
			}
			else {
				runOnUiThread(showExpired);
			}
			expDate = null;
			now = null;
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void loadListView(ListView lvAppontments, List<MobileAppointmentBrief> mobileAppointmentsBrief) {
		if (mobileAppointmentsBrief != null)
			m_appointment = new ArrayList<MobileAppointmentBrief>(mobileAppointmentsBrief);
		else
			m_appointment = new ArrayList<MobileAppointmentBrief>();
		m_adapter = new AppointmentAdapter(this, R.layout.appointment_brief_row, m_appointment);
		lvAppontments.setAdapter(m_adapter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return OptionsProvider.onCreateOptionsMenu(this, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return OptionsProvider.onOptionsItemSelected(this, item);
	}

	private class AppointmentAdapter extends ArrayAdapter<MobileAppointmentBrief> {
		
		private ArrayList<MobileAppointmentBrief> items;

		public AppointmentAdapter(Context context, int textViewResourceId, ArrayList<MobileAppointmentBrief> items) {
			super(context, textViewResourceId, items);
			this.items = items;
		}

		private void copyDate(Calendar fromTime, Calendar toTime) {
			toTime.set(Calendar.YEAR, fromTime.get(Calendar.YEAR));
			toTime.set(Calendar.MONTH, fromTime.get(Calendar.MONTH));
			toTime.set(Calendar.DAY_OF_MONTH, fromTime.get(Calendar.DAY_OF_MONTH));
			toTime.set(Calendar.DAY_OF_YEAR, fromTime.get(Calendar.DAY_OF_YEAR));
		}
		
		private void setupColorOfTime(TextView textView, Calendar now, Calendar interested) {
			if (interested.before(now)) {
				textView.setTextColor(Color.RED);
			}	
			else if (interested.after(now)) {
				textView.setTextColor(Color.GREEN);
			}
		}
		
		private void setupArriveAndDepartureSignatures(TextView beginTimeTextView, TextView endTimeTextView, String day, String begin, String end) throws Exception {
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DATEFORMAT);
			Date apptDay = simpleDateFormat.parse(day);
			Date beginDate = DateFormat.getTimeInstance(DateFormat.SHORT).parse(begin);			
			Date endDate = DateFormat.getTimeInstance(DateFormat.SHORT).parse(end);
			Calendar dayC = Calendar.getInstance();
			dayC.setTime(apptDay);
			Calendar now = Calendar.getInstance();
			Calendar apptTimeBegin = Calendar.getInstance();
			apptTimeBegin.setTime(beginDate);
			// copy current date
			copyDate(dayC, apptTimeBegin);
			setupColorOfTime(beginTimeTextView, now, apptTimeBegin);
			
			Calendar apptTimeEnd = Calendar.getInstance();
			apptTimeEnd.setTime(endDate);
			// copy current date
			copyDate(dayC, apptTimeEnd);
			setupColorOfTime(endTimeTextView, now, apptTimeEnd);
		}
		
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.appointment_brief_row, null);
			}
			MobileAppointmentBrief o = items.get(position);
			if (o != null) {
				TextView beginHour = (TextView) v.findViewById(R.id.tv_begin_hour);
				// TextView beginMinute = (TextView)
				// v.findViewById(R.id.tv_begin_minute);
				if (beginHour != null) {
					beginHour.setText(o.beginTime);

				}
				// if(bt != null){
				// bt.setText("Status: "+ o.getOrderStatus());
				// }
				TextView topBody = (TextView) v.findViewById(R.id.tv_top_body);
				if (topBody != null) {
					topBody.setText(o.appointmentTitle + " " + o.providerAs);
					topBody.setBackgroundColor(o.appointmentColor);
				}
				TextView bottomBody = (TextView) v.findViewById(R.id.tv_bottom_body);
				if (bottomBody != null) {
					bottomBody.setText(o.appointmentBody);
					bottomBody.setBackgroundColor(o.appointmentColor);
				}
				TextView endHour = (TextView) v.findViewById(R.id.tv_end_hour);

				if (endHour != null) {
					endHour.setText(o.endTime);
				}
				try {
					setupArriveAndDepartureSignatures(beginHour, endHour, o.date, o.beginTime, o.endTime);
				} catch (Exception e) {
					beginHour.setTextColor(Color.BLUE);
					endHour.setTextColor(Color.BLUE);
					e.printStackTrace();
				}
			}
			return v;
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent me) {
		this.detector.onTouchEvent(me);
		return super.dispatchTouchEvent(me);
	}

	@Override
	public void onSwipe(int direction) {
		String str = "";

		switch (direction) {

		case SimpleGestureFilter.SWIPE_RIGHT:
			loadDate(Calendar.DAY_OF_YEAR, -1);
			// dateToView.add(Calendar.DAY_OF_YEAR, -1);
			// tv_date.setText(String.format("%1$tm %1$te,%1$tY", dateToView));
			// showAppointments();

			break;
		case SimpleGestureFilter.SWIPE_LEFT:
			loadDate(Calendar.DAY_OF_YEAR, 1);
			// dateToView.add(Calendar.DAY_OF_YEAR, 1);
			// tv_date.setText(String.format("%1$tm %1$te,%1$tY", dateToView));
			// showAppointments();
			break;
		case SimpleGestureFilter.SWIPE_DOWN:
			str = "Swipe Down";
			break;
		case SimpleGestureFilter.SWIPE_UP:
			str = "Swipe Up";
			break;

		}
		// Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
	}

	void loadDate(final int day, final int offset) {
		Runnable loadAppointments = new Runnable() {
			@Override
			public void run() {
				dateToView.add(day, offset);

				showAppointments();
			}
		};
		Thread thread = new Thread(null, loadAppointments, "MagentoBackground");
		thread.start();
		m_ProgressDialog = ProgressDialog.show(Appointments.this, "Please wait...", "Retrieving data ...", true);

	}

	private Runnable returnRes = new Runnable() {

		@Override
		public void run() {
			tv_date.setText(String.format("%1$tm %1$te,%1$tY", dateToView));
			loadListView(lv_appontments, result.getMobileAppointmentsBrief());
			m_ProgressDialog.dismiss();
			m_adapter.notifyDataSetChanged();
		}
	};

	/**
	 * 
	 */
	private Runnable showExpired = new Runnable() {
		@Override
		public void run() {
			m_ProgressDialog.dismiss();
			Toast.makeText(getApplication(), "AEMobile demo period expired!", Toast.LENGTH_LONG).show();			
		}
	};
	
	@Override
	public void onDoubleTap() {
		Toast.makeText(this, "Double Tap", Toast.LENGTH_SHORT).show();
	}

}
